<template>
  <view class="table-code-draw">
    <canvas
      v-for="(item, index) in groups"
      :key="index"
      :canvas-id="`table-code${index}`"
      :style="{'width':`${width}rpx`,'height':`${item.height}rpx`}"
      class="code-img"
    ></canvas>
    <SaveButton text="保存" @click="onSave"></SaveButton>
  </view>
</template>

<script>
import { mapActions, mapState } from "vuex";
import SaveButton from "../../components/public/Button/SaveButton.vue";
export default {
  components: {
    SaveButton
  },
  data() {
    return {
      width: 750,
      height: 0,
      groups: [],
      lineSpace: 5,
      groupNameHeight: 25
    };
  },
  computed: {
    ...mapState({
      groupList: state => state.table.groupList
    })
  },
  onShow() {
    this.init();
  },
  methods: {
    ...mapActions({ getTableGroups: "getTableGroups" }),
    init() {
      const systemInfo = uni.getSystemInfoSync();
      const screenWidth = systemInfo.screenWidth; // 屏幕宽度
      const codeWidth = screenWidth / 2; // 二维码宽度
      this.groups = this.groupList.map(v => {
        const codeNum = v.tables.length; // 二维码个数
        const rowNum = Math.ceil(codeNum / 2); // 行数
        const height =
          rowNum * (this.width / 2 + (this.lineSpace / screenWidth) * 750) +
          (this.groupNameHeight / screenWidth) * 750; // canvas高度;
        const canvasHeight = rowNum * codeWidth + this.groupNameHeight + 100;
        return { ...v, height: height, canvasHeight: canvasHeight };
      });
      this.$nextTick(() => {
        this.drawGroupCode(this.groups);
      });
    },
    drawGroupCode(groups) {
      const systemInfo = uni.getSystemInfoSync();
      const screenWidth = systemInfo.screenWidth; // 屏幕宽度
      const codeWidth = screenWidth / 2; // 二维码宽度
      groups.forEach((group, index) => {
        let context = uni.createCanvasContext(`table-code${index}`);
        let codeNum = 0; // 二维码个数
        let x = 0;
        let y = 0;
        // context.fillStyle = "#ffffff";
        // context.draw();
        context.save();
        context.setFillStyle("#ffffff");
        context.fillRect(0, 0, screenWidth, group.canvasHeight);
        // context.draw();
        // context.drawColor("#ffffff");
        context.restore();
        context.setFontSize(20);
        context.textAlign = "center";
        context.fillText(group.name, codeWidth, 20);
        group.tables.forEach((table, tIndex) => {
          codeNum++;
          const rowNum = Math.floor((codeNum - 1) / 2); // 行数
          x = codeNum % 2 === 0 ? codeWidth : 0; // 二维码x坐标
          y = rowNum * (codeWidth + this.lineSpace) + this.groupNameHeight; // 二维码y坐标
          context.drawImage(table.tableCode, x, y, codeWidth, codeWidth);
          context.setFontSize(20);
          context.textAlign = "center";
          context.fillText(
            table.tableNo,
            ((codeNum - 1) % 2) * codeWidth + codeWidth / 2,
            y + codeWidth
          );
        });
        context.draw();
      });
    },
    canvasToTempFilePath(config) {
      return new Promise((reslove, reject) => {
        uni.canvasToTempFilePath({
          canvasId: config.canvasId,
          success: res => {
            reslove(res);
          },
          fail: error => {
            reject(error);
          }
        });
      });
    },
    saveImageToPhotosAlbum(config) {
      return new Promise((reslove, reject) => {
        uni.saveImageToPhotosAlbum({
          filePath: config.filePath, //保存的位置
          success: res => {
            reslove(res);
          },
          fail: error => {
            reject(error);
          }
        });
      });
    },
    async onSave() {
      let length = this.groups.length;
      let isError = false;
      for (let index = 0; index < this.groups.length; index++) {
        const g = this.groups[index];
        this.$showLoading(`正在保存第${index + 1}/${length}份`);
        try {
          let res1 = await this.canvasToTempFilePath({
            canvasId: `table-code${index}`
          });
          let res2 = await this.saveImageToPhotosAlbum({
            filePath: res1.tempFilePath
          });
        } catch (error) {
          isError = true;
        }
        if (index == this.groups.length - 1) {
          this.$hideLoading();
          if (!isError) {
            this.$toast(`成功保存${index + 1}份图片到相册`);
          } else {
            this.$toast(`保存失败`);
          }
        }
      }
    }
  }
};
</script>

<style lang="scss">
.table-code-draw {
  // min-height: 100%;
  height: 0;
  overflow: hidden;
  margin-bottom: 200rpx;
  // height: 100%;
  .code-img {
    // width: 100%;
    // height: 100%;
    margin-bottom: 10rpx;
    // visibility: hidden;
    // display: none;
  }
}
</style>
